// APP
if (window.plus) {
    ready();
} else {
    document.addEventListener('plusready', ready, false);
}

// Web
$(function () {
    if (AGENT_CLIENT.WEB) {
        ready();
    } else if (AGENT_CLIENT.APP) {
        $(".main").css("padding-bottom", "2px");
    }
});

// 初始化方法
function ready() {
    var _main = $(".main"), _conentheight = ($(window).height() - CONFIG_MANAGER.headerHight);
    var _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);

    var indexPage = function () {
        this.init();
    };

    indexPage.prototype = {
        // 初始化
        init: function () {
            this.loadads();
            this.loadSearchTag();
            this.bindEvent();
        },

        // 获取广告
        loadads: function () {
            var model = this;
            var nowtime = new Date(new Date().Format("yyyy-MM-dd")).getTime();
            var adslocatins = getLocalStorage(STORAGE_MANAGER.adslocatins);
            if (adslocatins && adslocatins.time >= nowtime) {
                this.paintPage(adslocatins.data);
                return;
            }

            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/ads/locatins/[APP-Home]"
            }).done(function (res) {
                if (res) {
                    model.paintPage(res);
                    setLocalStorage(STORAGE_MANAGER.adslocatins, {time: nowtime, data: res});
                }
            }).fail(function (res) {
                $.alert("请检查网络！");
            });
        },

        // 画页面
        paintPage: function (adslocatins) {
            this.setAdsImg(adslocatins);
            this.loadSoo();
        },

        // 设置首页广告图
        setAdsImg: function (locatins) {
            // 设置滚动广告
            var adslist = locatins["E0--1"];
            var bannerhtml = [];
            $.each(adslist, function (i, item) {
                var imgsrc = getImageUrl(item.path, 1080, 540);
                bannerhtml.push("<li><img src='" + imgsrc + "'  src='../../images/place/1080x540.png'  link='" + item.link + "' size='1080*540'></li>");
            });
            $(".slider ul").html(bannerhtml.join(""));

            // 轮播图
            $(".slider").touchSlider({
                width: $(window).width(),
                height: $(window).width() * 0.5013,
                during: 3000,
                autoplay: true,
                defaultimage: $("#defaultbannerimage")
            });

            // 设置其他图片
            var adsimglist = $("img[id^=adsE]");
            for (var i = 0; i < adsimglist.length; i++) {
                var adsimg = $(adsimglist[i]);
                var id = adsimg.attr("id");
                var tag = id.substr(3);
                var urllist = locatins[tag];
                if (!urllist) {
                    return;
                }
                var imgsrc = (urllist.length > 0) ? urllist[0].path : "../../images/grey.gif";
                var imglink = (urllist.length > 0) ? urllist[0].link : "";

                // 获取图片尺寸
                var imgwidth = 114, imgheight = 114;
                var sizestr = adsimg.attr("size");
                if (sizestr) {
                    var size = sizestr.split('*');
                    if (size.length == 2) {
                        imgwidth = size[0];
                        imgheight = size[1];
                    }
                }
                adsimg.attr({"data-original": getImageUrl(imgsrc, imgwidth, imgheight), link: imglink});
            }

            var shophtml = [];
            var e51 = locatins["E5--1"], e52 = locatins["E5--2"], e53 = locatins["E5--3"];
            var mksxdpwidth = $(window).width() * 0.67;
            $.each(e51, function (i, item) {
                var img2 = (e52.length > i) ? e52[i] : {path: "", link: ""};
                var img3 = (e53.length > i) ? e53[i] : {path: "", link: ""};

                shophtml.push("<div class='mksxdp' style='width: " + mksxdpwidth + "px'>");
                shophtml.push("<p class='syxdp1 mbboder'><a><img class='lazy'  src='../../images/place/439x460.png'  data-original='" + getImageUrl(item.path, 439, 460) + "' link='" + item.link + "'></a></p>");

                shophtml.push("<p class='syxdp2'>");
                shophtml.push("<span><a><img  class='lazy'  src='../../images/place/181x220.png'  data-original='" + getImageUrl(img2.path, 181, 220) + "'  link='" + img2.link + "'></a></span>");
                shophtml.push("<span class='margin5'><a><img class='lazy' src='../../images/place/181x220.png'  data-original='" + getImageUrl(img3.path, 181, 220) + "'  link='" + img3.link + "'></a></span>");
                shophtml.push("</p></div>");
            })
            $("#hotshoplistdiv").width(e51.length * (mksxdpwidth + 12)).html(shophtml.join(""));

            // 懒加载
            $('img.lazy').lazyload({
                event: "scroll",
                threshold: 100,
                failure_limit: 10
            });
            $('img.lazy').lazyload({
                event: "scroll",
                threshold: 100,
                container: $(".main"),
                failure_limit: 10
            });
        },

        // SOO快报
        loadSoo: function () {
            // Soo快报
            var _notice_count = 0, _notice_count_i = 0, _notice_isdesc = false, _notice_isfirst = true;
            var postdata = {index: 1, size: 10, search: {type: 1}};
            $.ajax({
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/news/lists"
            }).done(function (res) {
                var response = JSON.parse(res);
                var html = [];
                $.each(response.data, function (i, item) {
                    html.push("<li><a>" + item.content + "<span class='rejian'></span></a></li>");
                });
                $("#noticelist").html(html.join(""));
                _notice_count = response.data.length;
                var notice = setInterval(notice, 3000);
                // Soo快报
                function notice() {
                    if (_notice_count == 1) {
                        return;
                    }
                    // 第一次滚动
                    if (_notice_isfirst) {
                        _notice_count_i++;
                        _notice_isfirst = false;
                    }
                    $('#noticelist').animate({'margin-top': '-' + (40 * _notice_count_i) + 'px'}, 500);

                    if (_notice_count_i == (_notice_count - 1)) {
                        _notice_isdesc = true;
                    } else if (_notice_count_i == 0) {
                        _notice_isdesc = false;
                    }

                    if (_notice_isdesc) {
                        _notice_count_i--;
                    } else {
                        _notice_count_i++;
                    }
                }
            });
        },

        // 绑定事件
        bindEvent: function () {
            var model = this;
            // 置顶
            $("#gotop").on("tap", function () {
                _main.animate({scrollTop: '0px'}, 500);
            });

            var hasInitLoveItemList = false;
            // 判断是否显示置顶图片
            _main.scroll(function () {
                if (!hasInitLoveItemList) {
                    if ($("#loveitemlist").offset().top <= $(window).height() - 50) {
                        hasInitLoveItemList = true;
                        model.loadloveitemlist();
                    }
                }

                // 判断是否显示置顶
                model.isDisplayTopIcon();
            });

            // 扫一扫
            $("#btnscan").on("tap", function () {
                redirect("../barcode/barcodescan.html");
            });
            // 跳转消息页
            $("#btnmsg").on("tap", function () {
                redirect("../message/messagelist.html");
            });

            // 跳转搜索页
            $("#indexsearch").on("tap", function () {
                showSearchPage();
            });

            // 猜你喜欢
            $("#loveitemlist").on("tap", "li", function () {
                redirect("../goods/goodsdetail.html?id=" + $(this).attr("tip"));
            });

            //跳转页面
            $("#ul_nav>li").on("tap", function () {
                var jumpUrl = "";
                switch ($(this).attr("tip")) {
                    //商品分类
                    case "classification":
                        jumpUrl = "classification.html";
                        break;
                    //充值
                    case "charge":
                        jumpUrl = "../finance/selectRechargeAmount.html";
                        break;
                    //领星币
                    case "coinlist":
                        jumpUrl = "../coin/coinlist.html";
                        break;
                    //全民商探
                    case "apply":
                        jumpUrl = "../merchant/apply.html";
                        break;
                    //物流查询
                    case "orders":
                        jumpUrl = "../order/orders.html";
                        break;
                    //惠赚钱
                    case "earnmoney":
                        jumpUrl = "../earnmoney/earnmoney.html";
                        break;
                    //星粉联
                    case "invite":
                        jumpUrl = "../merchant/apply.html";
                        break;
                    //我的关注
                    case "attention":
                        jumpUrl = "../mine/attention.html";
                        break;
                    default:
                        break;
                }
                if (jumpUrl) {
                    redirect(jumpUrl);
                }
            });

            // 点击图片
            $("img[id^=adsE]").on("tap", function () {
                var link = $(this).attr("link");
                if (link) {
                    redirect(link);
                }
            });

            // 滚动广告
            $(".slider").on("tap", "img", function () {
                var link = $(this).attr("link");
                if (link) {
                    redirect(link);
                }
            });

            // 星店铺
            $("#hotshoplistdiv").on("tap", "img", function () {
                var link = $(this).attr("link");
                if (link) {
                    redirect(link);
                }
            });

            // 跳转星粉星币
            $("#btncoin").on("tap", function () {
                redirect("../coin/coinlist.html");
            });
        },

        // 搜索框中随机显示二级分类
        loadSearchTag: function () {
            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/goods/search/tag/1"
            }).done(function (res) {
                if (res && res.length > 0) {
                    var catagory = res[0];
                    $("#indexsearch p").text(catagory.name).attr("tip", catagory.catagory_no);
                    setLocalStorage(STORAGE_MANAGER.searchtag, {
                        catagory_no: catagory.catagory_no,
                        name: catagory.name
                    });
                }
            });
        },

        // 猜你喜欢
        loadloveitemlist: function () {
            if (!_currentloginuser) {
                return;
            }
            $.ajax({
                type: 'GET',
                url: CONFIG_MANAGER.RequstUrl + "v1/goods/rank/like/" + _currentloginuser.id + "/" + 6,
                beforeSend: function () {
                    $.showWaiting("猜你喜欢...");
                }
            }).done(function (res) {
                if (!res || res.length == 0) {
                    return;
                }
                var html = [];
                html.push("<h2 class='cnxhdbiaoti'><span class='bghui'>猜你喜欢的</span></h2>");
                html.push("<ul class='cnxhd'>");
                $.each(res, function (i, goodsitem) {
                    html.push("<li class='syxhd' tip='" + goodsitem.sku_id + "'><dl><dt><img class='lazy' data-original='" + getImageUrl(goodsitem.logo, 496, 466) + "' src='../../images/place/496x466.png'></dt><dd>" + goodsitem.name + goodsitem.title + "</dd><dd class='xhmony'>￥" + goodsitem.shop_price + "</dd></dl></li>");
                });
                html.push("</ul>");
                $("#loveitemlist").html(html.join(""));

                // 懒加载
                $('img.lazy').lazyload({
                    placeholder: "../../images/white.gif",
                    container: "#loveitemlist",
                    event: "scroll",
                    threshold: 100,
                    failure_limit: 10
                });

                _main.animate({scrollTop: ( _main.scrollTop() + $("#loveitemlist").offset().top - 100)}, 1200);
            }).always(function (res) {
                $.closeWaiting();
            });
        },

        // 判断显示置顶图标
        isDisplayTopIcon: function () {
            var top = _main.scrollTop();
            if (top > _conentheight / 2) {
                $("#gotop").show();
            } else {
                $("#gotop").hide();
            }
        }
    };

    var _indexPage = new indexPage();
}

// 关闭搜索页
function showSearchPage() {
    $("#searchiframe").show();
    searchiframe.window.show();
    searchiframe.window.loadSearchHistory();
}

// 关闭搜索页
function closeSearchPage() {
    $("#searchiframe").hide();
}